package org.example.day05;

/**
 * 第二章节2.2.9.2: 类锁 synchronized修饰静态方法，默认类锁是类.class。
 *                  和synchronized(类.class)效果一样.
 */
public class MyThread6 {
    //用到的锁是 MyThread6.class
    synchronized public static void printA(){
        try {
            System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printA的时间: " + System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printA: " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //用到的锁是 MyThread6.class 达到了同步
    synchronized public static void printB(){
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printB的时间: " + System.currentTimeMillis());
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printB: " + System.currentTimeMillis());
    }

    public static void main(String[] args) {
        MyThread6 m61 = new MyThread6();
        MyThread6 m62 = new MyThread6();
        Thread6A ta = new Thread6A(m61);
        ta.setName("A");
        ta.start();
        Thread6B tb = new Thread6B(m62);
        tb.setName("B");
        tb.start();
    }
}

class Thread6A extends Thread{
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.printA();
    }
}

class Thread6B extends Thread{
    private MyThread6 m6;

    public Thread6B(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.printB();
    }
}

